<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/9 0009
 * Time: 16:54
 */

namespace Cohuna\Models;
use Phalcon\Di;
use Phalcon\Mvc\Model\Message;

/**
 * 权限资源
 * @package Cohuna\Models
 */
class CohunaPermissionResource extends ModelBase
{
    public $resource_id;
    public $resource_name;
    public $display_name;
    public $controller_name;
    public $action_name;
    public $icon_class;
    public $parent_id;
    public $is_show_menu;
    public $sort_index;


    public function getSource()
    {
        return Di::getDefault()->getShared('config')->database->default->prefix . 'permission_resource';
    }

    public function validation()
    {
        if(empty($this->resource_name) || strlen($this->resource_name) > 100){
            $this->appendMessage(new Message('资源名不能为空且必须在100字内','resource_name'));
            return false;
        }
        if(empty($this->controller_name) || strlen($this->controller_name) > 100){
            $this->appendMessage(new Message('控制器名不能为空且必须在100字内','controller_name'));
            return false;
        }
        if(empty($this->action_name) || strlen($this->action_name) > 100){
            $this->appendMessage(new Message('方法名不能为空且必须在100字内','controller_name'));
            return false;
        }
        return true;
    }

    /**
     * 获取资源分组
     * @return array|null
     */
    public static function getPermissionResourceGroup()
    {
        $resource_list = static::find();
        if(empty($resource_list) === false){
            $controller_list = array();
            foreach ($resource_list as $resource){
                if(!array_key_exists($resource->controller_name,$controller_list) && $resource->is_show_menu){
                    $controller_list[$resource->controller_name] = array('name'=>$resource->display_name,'item'=>$resource);
                }
            }
            foreach ($resource_list as $resource){
                $controller_list[$resource->controller_name]['actions'][] = $resource;
            }
            return $controller_list;
        }
        return null;
    }
}